<template>
	<view>
		<u-navbar background="#fff" ref="nav" is-fixed back-text="返回" title="页面定制"></u-navbar>
		<view v-for="(item,index) in config" :key="index">
			<make-form :item="item" @outPut="getData"></make-form>
		</view>
		<view class="button">
			<u-button type="primary" @click="toLook">预览</u-button>
			<u-button type="primary" @click="release">保存</u-button>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				config: {},
			}
		},
		onLoad(e) {
			uni.showLoading({
				title: '获取模板'
			})
			wx.cloud.callFunction({
				name: "getTemplate",
				data: {
					_id: e.id,
					action: 'getTempitem'
				},
				success: res => {
					this.config = res.result.data
					this.$u.toast(res.result.msg)
				}
			})
		},
		methods: {
			// 转跳到预览页面
			toLook() {
				uni.setStorage({
					key: "config",
					data: this.config,
					success: () => {
						console.log("make",this.config);
						this.$u.route(`pages/index/look?id=toLook`)
					}
				})
			},
			// 获取子组件返回的值
			getData(v) {
				this.config[v.key].info = v.info
				if (v.key == 'bg') {
					this.config.temp.cover = v.info
				}
			},
			// 发布到服务器
			release() {
				uni.showLoading({
					title: '上传中…'
				})
				const config = this.config
				const date = new Date().getTime()
				const login = uni.getStorageSync('login')
				
				if (login === '') {
					uni.showModal({
						title: '提示',
						content: '请先登陆过后在尝试制作同款',
						showCancel: false,
						confirmText: '前往登录',
						success: () => {
							uni.switchTab({
								url: '/pages/mine/index'
							})
						}
					})
				} else {
					const login = uni.getStorageSync('login')
					config.temp = {
						bessing: 0,
						_id: config._id,
						info: login.nickName,
						cover: config.bg.info,
						avatar: login.avatarUrl,
						template: this.config.temp.template,
						time: this.$u.timeFormat(date, 'yyyy-mm-dd hh:MM')
					}
					wx.cloud.callFunction({
						name: "uploadTemplate",
						data: {
							config: {
								...config,
								_openid: login._openid,
								is_template: 'index'
							}
						},
						success: res => {
							console.log(res);
							this.$u.toast("上传成功")
							this.$u.route(`pages/index/look?id=${res.result}`)
							this.status = "nomore"
						},
						fail: err => {
							this.$u.toast("上传失败")
							console.log("err", err);
							this.status = "nomore"
						}
					})
				}
			}
		}
	}
</script>
<style>
	/* 设置全局属性 */
	page {
		background-color: #fff;
	}
</style>

<style lang="scss" scoped>
	.button {
		display: flex;
		width: 710rpx;
		margin: 20rpx;
		justify-content: space-between;

		u-button {
			width: 345rpx;
		}
	}
</style>
